#! /usr/bin/env python
# -*- coding: utf-8 -*-

#======================================= init =================================

import sqlite3

tabname = 'webbench'
dbfile = 'webbench.db'

#初始化
def init():
    existTabSql = 'select count(*) from sqlite_master where type = "table" and name = "%s"' % tabname
    createTabSql = 'create table %s(id integer primary key autoincrement, client varchar(4), sec varchar(50), url varchar(50), speed varchar(50), requests varchar(50), strtime varchar(50))' % tabname
    con = sqlite3.connect(dbfile)
    cur = con.cursor()
    cur.execute(existTabSql)
    existstatus = cur.fetchone()[0]
    if not existstatus:
        cur.execute(createTabSql)
        con.commit()
    con.close()

#======================================= dao ==================================

#执行事务性操作
def execute(sql):
    con = sqlite3.connect(dbfile)
    cur = con.cursor()
    cur.execute(sql)
    con.commit()
    con.close()
    
#执行查询操作
def fetch(sql):
    con = sqlite3.connect(dbfile)
    cur = con.cursor()
    cur.execute(sql)
    data = cur.fetchall()
    con.close()
    return data

#======================================= mode =================================

import web, re, os, datetime

urls = (
    '/.*', 'index'
)
app = web.application(urls, locals())
render = web.template.render('templates/')

class bench:
    c = ''
    t = ''
    url = ''
    speed = ''
    requests = ''
    data = ''
    msg = ''
    
    def __init__(self):
        pass
    
    def save(self):
        curdate = datetime.datetime.now()
        sql = 'insert into %s values(null, %s, %s, "%s", "%s", "%s", "%s")' % (tabname, self.c, self.t, self.url, self.speed, self.requests, str(curdate))
        execute(sql)
        
    def setData(self):
        sql = 'select * from %s order by id desc limit 10 ' % tabname
        self.data = fetch(sql)
        
    def setMsg(self):
        self.msg = 'Benchmarking: GET %s\n\r%s clients, running %s sec.\n\r%s.\n\r%s' % (self.url, self.c, self.t, self.speed, self.requests)

class index:
    
    def GET(self):
        b = bench()
        b.setData()
        return render.webbench(b)
    
    def POST(self):
        b = bench()
        i = web.input(c = '', t = '', url = '')
        b.c, b.t, b.url = i.c, i.t, i.url
        if i.c != '' and i.t != '' and i.url != '':
            cmdStr = '/usr/local/bin/webbench -c %s -t %s "%s"' % (i.c, i.t, i.url)
            output = os.popen(cmdStr)
            str = output.read()
            reSpeed = re.search('Speed.*sec', str, re.I)
            reRequests = re.search('Requests.*failed', str, re.I)
            if reSpeed != None:
                b.speed = reSpeed.group(0)
            if reRequests != None:
                b.requests = reRequests.group(0)
            b.setMsg()
            b.save()
        b.setData()
        return render.webbench(b)


if __name__ == '__main__':
    init()
    app.run()

